package com.gjx.leetcode;

import java.util.LinkedList;
import java.util.Queue;

//117. 填充每个节点的下一个右侧节点指针 II
//
//给定一个二叉树
//
//struct Node {
//  int val;
//  Node *left;
//  Node *right;
//  Node *next;
//}
//填充它的每个 next 指针，让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点，则将 next 指针设置为 NULL。
//
//初始状态下，所有 next 指针都被设置为 NULL。
//
// 
//
//示例：
//
//
//
//输入：{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
//
//输出：{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}
//
//解释：给定二叉树如图 A 所示，你的函数应该填充它的每个 next 指针，以指向其下一个右侧节点，如图 B 所示。
// 
//
//提示：
//
//你只能使用常量级额外空间。
//使用递归解题也符合要求，本题中递归程序占用的栈空间不算做额外的空间复杂度。

public class Solution117 {
	public Node connect(Node root) {
		if (root == null) {
			return null;
		}

		Node brother = null;
		
		Node next = root.next;
		
		while (next != null) {
			if (next.left != null) {
				brother = next.left;
				break;
			}
			if (next.right != null) {
				brother = next.right;
				break;
			}
			next = next.next;
		}
		
		if (root.left != null) {
			
			if (root.right != null) {
				root.left.next = root.right;
			} else if (brother != null) {
				root.left.next = brother;
			}
			
		}
		
		if (root.right != null) {
			root.right.next = brother;
		}
		
		connect(root.right);
		connect(root.left);
		
		return root;
	}
	
	
	public static void main(String[] args) {
		
		Node root = new Node(1, null, null, null);
		root.left = new Node(2, null, null, null);
		root.right = new Node(3, null, null, null);
		root.left.left = new Node(4, null, null, null);
		root.left.right = new Node(5, null, null, null);
		root.right.left = new Node(6, null, null, null);
		root.right.right = new Node(7, null, null, null);
		root.left.left.left = new Node(8, null, null, null);
		root.left.right.left = new Node(9, null, null, null);
		root.left.right.right = new Node(10, null, null, null);
		root.right.right.left = new Node(11, null, null, null);
		root.right.right.right = new Node(12, null, null, null);
		root.left.right.right.left = new Node(13, null, null, null);
		
		
		new Solution117().connect(root);
		System.out.println(root);
	}
	
}
